// 路由配置
import $router from '@/router'
import $ajax from '../$ajax';
import $app from '../$app';
import $store from '@/store';
import Vue from 'vue';

export default {
	//404图片，加载默认图
	defImag(event) {
		let img = event.target;
		img.src = $app.defImag404;
		img.onerror = null; //防止闪图
	},
	//在线支付的type
	payInline: [
		{//实用新型专利提交
			type: 100,
			name: 'patentDoSYXX',
			infoPage: 'patentDetails'
		},
		{//外观专利提交
			type: 101,
			name: 'patentDoWGZL',
			infoPage: 'patentDetails'
		},
		{//发明专利提交
			type: 102,
			name: 'patentDoFMZL',
			infoPage: 'patentDetails'
		},

		{//商标注册
			type: 200,
			name: 'trademarkDoZC',
			infoPage: 'tmDetails'
		},
		{//商标担保注册
			type: 209,
			name: 'trademarkDoDB',
			infoPage: 'tmDetails'
		},
		{//美术作品著作权登记
			type: 300,
			name: 'copyrightDoMS',
			infoPage: 'msDetails'
		},
		{//软件著作权登记
			type: 302,
			name: 'copyrightDoRJ',
			infoPage: 'rjDetails'
		}
	],
	//登录后存token 
	//globalUrl全局性参数，登录成后跳去哪里？空=》去首页
	//resData 可以是对象，可以是字符串；
	//judge:false短期登录，true永久登录
	//buEr 参数仅作为大屏小屏的切换判断
	saveToken(globalUrl, resData, judge, buEr) {
		let token = '';
		if (typeof resData === 'object') {
			token = resData.api_token;
		} else {
			token = resData;
		}

		// console.log('ok = ', token)

		let now = new Date().getTime();

		let time = '';
		if (!!judge) {
			time = now + $app.foreverTime();//永久登录
		} else {
			time = now + $app.exTime();//短期登录
		}

		$app.setLocal({ time, token }, 'token');
		if ($app.judgeData(globalUrl)) {//globalUrl 参数存在，跳去这个参数页
			$router.replace({ path: `/${globalUrl}` });
		} else {//globalUrl 参数不存在，跳去首页
			$router.replace({ name: 'home' });
		}



		//buEr 参数仅作为大屏小屏的切换判断
		if (buEr) {
			$app.minScreenColl();
		}

		$ajax.mGlistAll({fcgparent:0});//商标45分类存一次本地 => 日后直接取本地的既可以
	},

	//小屏自动折叠函数
	minScreenColl() {

		let oldName = '';
		setTimeout(() => {
			oldName = $router.history.current.name;
		}, 1000);

		setTimeout(() => {

			// 正式，线上环境
			if (process.env.NODE_ENV === 'production') {
				if ($router.history.current.name != 'login' && $router.history.current.name == oldName) {//登录页不判断


					$store.commit('upData_collapsed',$app.isMinScreen());
					if ($app.isMinScreen()) {
						Vue.prototype.$Notice.info({
							title: '导航自动折叠',
							desc: '当前为小屏幕，可点击左上角展开导航。'
						});
					}


				}

				if ($router.history.current.name != 'login') {
					$app.rightMessageBox();//全局性右边弹消息框

					// 30秒ping一次
					setInterval(() => {
						$app.rightMessageBox();//全局性右边弹消息框
					}, 30000);
				}
			} else {
				// console.log('测试服=>导航栏折叠功能：关闭，消息主推：关闭')
			}

		}, 2000);

		




	},

	//全局性右边弹消息框
	rightMessageBox() {

		// websocket 主推
		$app.ws("ping", {}, res => {
			// 全局系统消息
			if (res.type == "partnerMsg") {
				console.log("websocket = ", res.data);
				$store.commit('upData_messages',res.data.unread_msg_count);//右上角头像 未读消息

				let list = res.data.list;
				list.forEach((val, i) => {
					// val.link_url='/patentDetails?order_id=6873';
					// 未读消息
					if (val.is_read == 0) {
						Vue.prototype.$Notice.open({
							title: val.title,
							render: h => {
								let out = [];
								out.push(
									h(
										"div",
										{ class: "marginB10 txtOneLine c999" },
										val.content
									)
								);

								let btnList = [];
								// 立刻处理
								if ($app.judgeData(val.link_url)) {
									btnList.push(
										h(
											"span",
											{
												class:
													"cRed textLine textRight f_12 marginR20 f_bold",
												on: {
													click: () => {
														//标记已读
														$ajax.pTreadMsg(val.id, resData => {
															$store.commit('upData_messages',resData.unread_msg_count);//右上角头像 未读消息
														});

														$router.push(val.link_url);
														Vue.prototype.$Notice.destroy(); //销毁弹框
													}
												}
											},
											"立即处理"
										)
									);
								}

								btnList.push(
									h(
										"span",
										{
											class: "cBlue textLine textRight f_12",
											on: {
												click: () => {
													$app.msShowBox(val.title, val.content, val.id, val.link_url, true);
													Vue.prototype.$Notice.destroy(); //销毁弹框
												}
											}
										},
										"查看详情"
									)
								);

								out.push(h("div", { class: " textRight f_12" }, btnList));

								return out;
							}
						});
					}
				});
			}
		});

	},

	//登录判断 globalUrl=>地址栏上的传值,
	//格式如下：xxxxxx.xxx/#/xxxx?globalUrl=patentThird?order_id=9481
	//globalUrl => patentThird?order_id=9481
	getTokenFun(globalUrl, success, fail) {

		// console.log('全局总路由，获取参数 globalUrl = ',globalUrl);

		let obj = $app.getLocal('token');
		if ($app.judgeData(obj)) {
			let { time, token } = obj;
			let nowTime = new Date().getTime();//获取现在的时间
			if (nowTime > time) {//已经超出了登录期限
				$app.initAjaxBase(() => {
					$app.toast($app.tokenOverTips, false, () => {
						$app.goLogin(true, globalUrl);
					});
				});
			} else {
				success(token, nowTime);
			}
		} else {
			if (fail instanceof Function) {
				fail();
			} else {
				console.log('完全没有token')
				$app.initAjaxBase(() => {
					$app.goLogin(false, globalUrl);
				});
			}

		}
	},

	//强制性跳去登录
	goLogin(reload, param) {
		$app.loginOutClear(() => {
			if (!!reload) {
				$app.goTargetUrl(param);
			} else {
				$app.goTargetVue(param);
			}

		});
	},
	//传统方式刷新页面去到指定目标
	goTargetUrl(param) {
		if (!!param) {

			let url = window.location.href;
			let xuT = url.indexOf("/#/");
			let urlP = $app.superSlice(url, 0, xuT + 3);

			window.location.replace(urlP + param);
		} else {
			window.location.reload(true);//这个页面，刷页面 万物初始
		}
	},
	// 配合上着适用
	goTargetVue(param) {
		if ($app.judgeData(param)) {
			//路由登录
			$router.replace({
				name: 'login',
				query: {
					globalUrl: param
				}
			});
		} else {
			//路由登录
			$router.replace({ name: 'login' });
		}
	},
	//总路由控制器
	routerRoot(to, callBack) {
		
		//公共接口: 国家=》先存一次
		$ajax.countryList();

		// 版权 地区联动=》先存一次
		$ajax.getAreaList(0);

		// 专利 地区联动=》先存一次
		$ajax.cpcAreaList('');




		//更新屏幕宽高
		$app.winHeight = window.innerHeight;
		$app.winWidth = window.innerWidth;

		$app.userHasCompanyAll();// 获取企业配置
		$app.userHasUserPower(to, callBack);// 获取用户配置

	},

	// 获取企业配置
	userHasCompanyAll() {
		let companyAll = $app.getSession('companyAll');
		if (!$app.judgeData(companyAll)) {//没有存储
			$ajax.pInfo(resData => {//获取企业信息
				if ($app.judgeData(resData) && $app.judgeData(resData.head_img_path) && $app.judgeData($app.getVal_fileUrl(resData.head_img_path)) ) {
					
					$store.commit('upData_userImg',$app.getVal_fileUrl(resData.head_img_path));//赋值给全局 头像
					
				}
			});
		} else {//有存储
			if ($app.judgeData(companyAll.head_img_path) && $app.judgeData($app.getVal_fileUrl(companyAll.head_img_path))) {
				
				$store.commit('upData_userImg',$app.getVal_fileUrl(companyAll.head_img_path));//赋值给全局 头像
				
			}
		}
	},
	// 获取用户配置
	userHasUserPower(to, callBack) {
		let userPower = $app.getSession('userPower');
		if (!$app.judgeData(userPower)) {
			$ajax.userInfo(resData => {//再获取用户信息

				let {
					has_password,
					is_bind_min_program //false没有关注过小程序
				} = resData;

				
				// 关注微信公众号没有？判断弹框
				if (!$store.state.F_cat.wechatBoxFinal) {

					$store.commit('upData_wechatBoxFinal');//弹框只弹一次，就不弹了

					if (!is_bind_min_program) {//显示弹框二维码
						$store.commit('upData_wechatBox');
					};
				}
				

				//公共配置
				$ajax.bigSetting();
				$app.userHasPassword(has_password, to, callBack);//强制性填密码
			});
		} else {
			//公共配置
			$ajax.bigSetting();
			$app.userHasPassword(userPower.has_password, to, callBack);//强制性填密码
		}
	},

	//判断有没有设置密码
	userHasPassword(has_password, to, callBack) {
		callBack();

		// 以下的逻辑老板还没有定，暂 屏蔽
		// if ($app.judgeData(has_password)) {//有密码
		// 	callBack();
		// } else {//没有密码
		// 	if (to.name == "home") {//目标页是首页
		// 		callBack();
		// 	} else {//强制性跳去首页 设置密码
		// 		callBack();
		// 	}
		// }

	},

	// 退出清楚所有存储
	loginOutClear(callBack) {

		//删除所有 localStorage
		($app.objToArray(1, window.localStorage)).forEach((val, i) => {
			if (val == 'patentWriteTips' || val == 'root_cpcAreaList' || val == 'root_countryList' || val == 'root_getAreaList') {
				//有几个东西永远存在本地 方便日后直接读取，速度更快
			} else {
				$app.removeLocal(val);
			}
		});

		//删除所有 sessionStorage
		sessionStorage.clear();

		callBack instanceof Function && callBack();
	},


	//商品分类返回值
	tlOut(num, obj, callBack) {
		let out = '';
		if (num == 1) {//1专利
			out = obj[0];
		} else if (num == 2) {//2商标
			out = obj[1];
		} else if (num == 3) {//3版权
			out = obj[2];
		} else {
			out = obj;
		}
		callBack(out);
	},

	/**
	 * 所有图片统一处理
	 * obj:0直接返回base64图片，1营业执照,2专利文件,3身份证,4外观设计图片,5外观说明文件,6软著文件,7美术著作文件,8商标文件
	 * obj=》{type:xxx}身份证 或 营业执照 识别
	 * */
	allImgDo(obj, file, base64, callBack, fail) {

		//身份证 或 营业执照文字识别
		if (typeof obj === 'object') {//对象
			//身份证识别 或 营业执照识别
			$ajax[obj.type](base64, resData => {
				callBack(resData, $app.deleJHz(file.name));
			}, fail);
		} else if (parseInt(obj) > 0) {//数字
			//图片上传后台转成 jpg格式
			$ajax.uploadImage(obj, base64, file.name, callBack, fail);
		} else {
			callBack(base64, $app.deleJHz(file.name));
			fail instanceof Function && fail();
		}

	},

	//后台返回错误码，input自动聚焦
	failFocus(res, that) {
		if (res[$app.xhrCode] == 500) {
			let resData = res.data;
			that.$Message.error({ content: res[$app.xhrMsg] });
			if ($app.judgeData(resData)) {
				that.$refs[resData].focus();
			}
		}
	},

	//手机框失去焦点，判断处理
	//type：1注册用；2登录+修改密码用
	ttxT(type, that) {
		let { mobile } = that;
		if ($app.telCheck(mobile)) {//手机正则匹配满足
			//判断手机是否已经注册
			$ajax.checkMobile(mobile, type, that);
		}

	},
	//强制性跳转企业认证
	companyYes(companyAll, callBack) {
		// 未认证 强制跳转
		if (!$app.judgeData(companyAll) || companyAll.state == 0) {
			//页面跳转
			$router.push({
				name: 'accountInfo',
				query: {
					companyGo: 1
				}
			});
			callBack instanceof Function && callBack();
			
		} else if ($app.judgeData(companyAll)) {
			let state = companyAll.state;
			switch (parseInt(state)) {
				// 0未认证,1认证中,2认证成功,3认证未通过,4已注销
				case 1:
					$app.toast('您的账号认证中，请耐心等待', true);
					break;
				case 2:
					callBack instanceof Function && callBack();
					break;
				case 3:
					//页面跳转
					$router.push({
						name: 'accountInfo',
						query: {
							companyGo: 1
						}
					});
					callBack instanceof Function && callBack();
					
					break;
				case 4:
					$app.toast('您的账号已注销，请联系客服人员', false);
					break;
			}
		}

	},

	//强制性跳转充值
	rechargeYes(callBack) {
		//页面跳转
		$router.push({
			name: 'accountInfo',
			query: {
				rechargeYes: 1
			}
		});
		callBack instanceof Function && callBack();
	},
	// 增值服务，今天用完，强制性跳去充值页面
	todayMoneyYes(service_type, callBack) {
		
		$router.push({
			name:'accountInfo',
			query: {
				TC_type: service_type
			}
		});
		

		callBack instanceof Function && callBack();

		
	},



	//立即注册+忘记密码+短信登录 3处地方用到这个函数 
	// login2、login3、login4 必须包含以下数据：captcha, mobile, tchaObj , phoneOk
	loginGetCodeFun(that, num, dom) {

		let { captcha, mobile, tchaObj, phoneOk } = that;



		if (!$app.telCheck(mobile)) {
			that.$Message.error({ content: '请输入正确的手机格式，勿含空格等特殊字符' });
			that.$refs['mobile'].focus();
		} else if (!phoneOk && num != 2) {
			if (num == 1) {
				that.$Message.error({ content: '该手机号已注册' });
			} else if (num == 3) {
				that.$Message.error({ content: '该手机号未注册' });
			}
			that.$refs['mobile'].focus();
		} else if (!$app.judgeData(captcha)) {
			that.$Message.error({ content: '图形验证码不能为空' });
			that.$refs['captcha'].focus();
		} else {
			$ajax.sendCode(captcha, mobile, num, tchaObj.key, () => {
				that.$Message.success({ content: '验证码发送成功' })

				let time = 120;

				that.btnDisabled = true;

				document.getElementById(dom).innerHTML = `等待${time}s`;


				//设置定时器 每1秒钟 执行一次
				let timeDown = setInterval(() => {
					let getDom = document.getElementById(dom);
					if ($app.judgeData(getDom)) {
						//time自身减1
						time--;
						document.getElementById(dom).innerHTML = `等待${time}s`;

						//如果到0
						if (time == 0) {
							//清除定时器
							clearInterval(timeDown);
							// 按钮样式复原
							that.btnDisabled = false;
							document.getElementById(dom).innerHTML = '重新发送';
						}
					} else {
						//清除定时器
						clearInterval(timeDown);
						// 按钮样式复原
						that.btnDisabled = false;
					};
				}, 1000);

			}, that);
		}
	},
	//删除订单按钮
	delOrderSure(id, callBack) {
		$app.confirm('确定删除该订单？', '温馨提示', {
			yesFun: () => {
				$ajax.orderDel(id, resData => {
					callBack();
				})
			}
		});
	},

	//已下单，未付款前：详情跳转编辑页面，修改订单信息
	goEdit(that) {

		$app.goEditTT(that);

	},
	// 配合上者使用
	//专利+商标+版权 =》 专用
	goEditTT(that) {
		let {
			$route: {
				name,
				query: { order_id },
				query,
				params
			},
			orLiInfo: { goods_type: type }
		} = that;

		let nameDo = "";
		$app.payInline.forEach((val, i) => {
			type == val.type && (nameDo = val.name);
		});

		//关闭已有页面 同名字的路由值出现一个
		$app.closeHadPage(nameDo, () => {
			$app.closeTag({ name, params, query }); // 关闭本页面

			//页面跳转
			$router.push({
				name: nameDo,
				query: { order_id, type }
			});
		});
	},

	//专利打包服务
	goEditDB(order_id, orLiInfo) {

		let {
			goods_type,
			goods_id
		} = orLiInfo;
		$app.goEditDpeiH(1, order_id, goods_type, goods_id, false);
	},

	// 配合上面两者适用 doW:1保留本页，2关闭本业
	goEditDpeiH(doW, order_id, goods_type, goods_id, second) {
		$app.closeHadPage('patentDoAllIn', () => {
			if (doW == 1) {
				//保留本业
			} else {
				$app.closeTag($router.history.current);// 关闭本页面
			}
			let query = {
				order_id,
				type: goods_type,
				goodsId: goods_id,
				sTitle:'资料填写'
			};
			if (second) query.second = second;
			//页面跳转
			$router.push({
				name: 'patentDoAllIn',
				query
			});
		});
	},


	// 跳转系统内，设置了缓存的页面，
	// closePage 关闭父页面：true关,false或空 不关
	goSaKnowP(type, tm_name, closePage) {
		let nameDo = "";
		$app.payInline.forEach((val, i) => {
			type == val.type && (nameDo = val.name);
		});

		//关闭已有页面 同名字的路由值出现一个
		$app.closeHadPage(nameDo, () => {

			if (!!closePage) {
				$app.closeTag($router.history.current); // 关闭本页面
			}

			//页面跳转
			$router.push({
				name: nameDo,
				query: {
					type,
					tm_name,
				}
			});
		});
	},


	//商标补正
	goEditTm(that, id) {
		let {
			$route: {
				query: { order_id },
			},
			goods_type: type
		} = that;

		let nameDo = "";
		$app.payInline.forEach((val, i) => {
			type == val.type && (nameDo = val.name);
		});

		//关闭已有页面 同名字的路由值出现一个
		$app.closeHadPage(nameDo, () => {
			$app.closeTag($router.history.current); // 关闭本页面

			//页面跳转
			$router.push({
				name: nameDo,
				query: { order_id, type, id }
			});
		});
	},

	//删除订单 这个方法 - 订单详情内部 - 的删除按钮时候
	delOrderOk(id) {
		$app.delOrderSure(id, () => {
			$app.closeTag($router.history.current); // 关闭本页面
		});
	},

	// 判断下面一层有没有 file_url
	package_file_url(obj) {
		let out = false;
		if ($app.judgeData(obj) && $app.judgeData($app.getVal_fileUrl(obj))) {
			out = true;
		}
		return out;
	},


	copyright_SW(params) {
		let bigOk = '';

		let {
			row: {
				copyright_software, copyright_work
			}
		} = params;


		if ($app.judgeData(copyright_software)) {//软件著作
			bigOk = copyright_software;
			bigOk.bigName = copyright_software.software_name;
		} else if ($app.judgeData(copyright_work)) {//美术著作
			bigOk = copyright_work;
			bigOk.bigName = copyright_work.works_name;
		}


		return bigOk;

	},


	imgBoxSee(src) {
		
		if (src.indexOf('img404') > -1) {
			Vue.prototype.$Message.error({ content: '图片加载失败' });
		} else {
			Vue.prototype.$Modal.info({
				okText: '',
				width: 600,
				render: (h) => {
					let out = h("img", {
						class: ` width100 `,
						attrs: {
							src
						},
					});
					return out;
				}
			});
		}
	},
	//通过type区分 100-199专利，200-299商标，300-399版权
	goodsBigClass(type) {// 1专利 2商标 3版权
		let out = (type.toString()).slice(0, 1);
		return out;
	},






	



	//商标45类，总数计算
	zongGo(cglist) {
		let out = 0;

		cglist.forEach((val, i) => {
			if ($app.judgeData(val.editList)) {
				out += val.editList.length;
			}
		});

		return out;
	},
	// 新旧算法兼容 
	editList_or_items(val){
		let out='';
		//新算法 editList or items 只有一人会存在
		//必须优先判断 editList 否则会报错
		if ($app.judgeData(val.editList)) {
			out = (val.editList)
		} else {
			out = (val.items)
		}
		return out;
	}, 
	// 总数计算
	zongXuJ(arr) {
		let out = 0;

		arr.forEach((val, i) => {
			out += $app.editList_or_items(val).length;
		});

		return out;
	},
	// 总价格计算 正常流程
	zongJiaJ(arr) {
		return $app.zongJiabase(arr, 1);
	},
	// 新算法
	z_XHuan(cglist) {
		let cg_list = [];
		if ($app.judgeData(cglist)) {
			cglist.forEach((val, i) => {
				let {
					fcgid,
					fcgname,
					fcgnum,
					editList
				} = val;

				if ($app.judgeData(editList)) {
					cg_list.push({
						fcgid,
						fcgname,
						fcgnum,
						editList,
					});
				}
			})
		}
		return cg_list;
	},
	zongXuJ_t(cglist) {
		let out = 0;
		let arrT = $app.z_XHuan(cglist);
		return out;
	},
	// 担保注册
	zongJiaDb(arr) {
		return $app.zongJiabase(arr, 2);
	},
	//配合上者使用 who：1普通注册，2担保注册
	zongJiabase(arr, who) {
		let {
			tm_register,
			tm_guarantee_register
		} = $app.getSession('bigSetting');

		let base_official_fee, base_service_fee, item_fee;

		if (who == 1) {
			base_official_fee = tm_register.base_official_fee;
			base_service_fee = tm_register.base_service_fee;
			item_fee = tm_register.item_fee;
		} else if (who == 2) {
			base_official_fee = tm_guarantee_register.base_official_fee;
			base_service_fee = tm_guarantee_register.base_service_fee;
			item_fee = tm_guarantee_register.item_fee;
		}


		let money = {
			allK: parseFloat(base_official_fee) + parseFloat(base_service_fee),
			item_fee: parseFloat(item_fee)
		}

		let out = 0
		arr.forEach((val, i) => {

			if ($app.editList_or_items(val).length > 10) {
				out += money.allK + ($app.editList_or_items(val).length - 10) * money.item_fee
			} else {
				out += money.allK
			}
		})

		return out
	},

}; 